package com.alibaba.travel.thirdpart.controller;

import com.alibaba.travel.common.utils.R;
import com.alibaba.travel.thirdpart.config.OSSPropertiesConfig;
import com.aliyun.oss.OSSClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: where
 * @Date: 2023/03/06/10:30
 * @Description:
 */
@Api(tags = {"OSS文件上传功能"})
@RestController
@RequestMapping("/thirdpart/oss/")
public class OssController {
    @Autowired
    private OSSPropertiesConfig ossConfig;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        if (ObjectUtils.isEmpty(file)) {
            return R.error("文件错误");
        }
        // 1、OssClient初始化
        OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getKeyId(), ossConfig.getKeySecret());
        // 2.文件名称
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + filename;
        // 父文件夹
//        String date = DateUtils.getCurrentDate();
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String date = format.format(new Date());
        System.out.println(date);
        filename = date + "/" + filename;

        // 3.保存地址
        ossClient.putObject(ossConfig.getBucketName(), filename, file.getInputStream());

//        System.out.println(file);

        // 返回url
        //https://xppll.oss-cn-beijing.aliyuncs.com/01.jpg
        String url = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + filename;
        //关闭OSSClient
        ossClient.shutdown();

        return R.ok().put("url", url);
    }



    /**
     * 下载文件
     */
    /*public String download(String url) {
        // 创建OSSClient实例。  OSSClientBuilder ：3.1.0版本
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getKeyId(), ossConfig.getKeySecret());
        try {
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            // url：com后的位置为objectName
            String objectName = url.substring(1);
            OSSObject ossObject = ossClient.getObject(ossConfig.getBucketName(), objectName);

            // 读取文件内容。
            System.out.println("Object content:");
            BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
            while (true) {
                String line = reader.readLine();
                if (line == null) break;

                System.out.println("\n" + line);
            }
            // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            reader.close();
            // ossObject对象使用完毕后必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            ossObject.close();

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "success";
    }*/
}
